import sys
import os
import subprocess
from db import DBClient
from urllib.request import urlopen
import json
import time


BaseDir = "/usr/share/nginx/html/logs"

print(sys.argv)


client = DBClient()
task = client.get_task(sys.argv[1])

TaskDir = os.path.join(BaseDir, str(task["_id"]))

try:
    os.makedirs(TaskDir)
except FileExistsError:
    pass


class RightException(Exception):
    pass


class ErrorException(Exception):
    pass


def sttime(m):
    _s = "%Y-%m-%dT%H:%M:%S.000Z"
    print(m)
    start =  time.strptime(m[0], _s)
    end =  time.strptime(m[1], _s)
    start = (start.tm_hour * 3600 + start.tm_min * 60 + start.tm_sec + (8*3600))% (3600*24)
    end = (end.tm_hour * 3600 + end.tm_min * 60 + end.tm_sec + (8*3600)) % (3600 * 24)
    return start, end

def get_right(name, arguments):
    a = arguments['now']
    second = a.hour * 3600 + a.minute * 60 + a.second
    data = json.loads(urlopen("http://172.16.50.89:5000/right/?time={0}".format(second)).read().decode("utf8"))
    rights = data['rights']
    for i in rights:
        if i['name'] == name:
            _min, _max = sttime(i['time'])
            if _min < second and second < _max:
                return i['right']
            else:
                break
    return False

for _id, step in enumerate(task['steps']):
    book = step['playbook']
    try:
        step_dir = os.path.join(TaskDir, str(_id))
        try:
            os.makedirs(step_dir)
        except FileExistsError:
            pass
        playbook = task['steps'][_id]['playbook']
        data = urlopen(playbook).read()
        with open(os.path.join(TaskDir, str(_id) ,"go.yaml"), "w") as f:
            f.write(data.decode("utf8"))

        with open(os.path.join(TaskDir, str(_id), "hosts"), "w") as f:
            f.write("[webservers]\n")
            f.write(task['arguments']['host'])

        params = ["ansible-playbook", "-i", "hosts", "go.yaml"]
        for i in task['arguments'].keys():
            params.append("-e")
            params.append("{0}={1}".format(i, task["arguments"][i]))
        log = open(os.path.join(step_dir, "log.txt"), "w")
        if not get_right(task['steps'][_id]['right'], task['arguments']):
            log.write("You don't have right {0}".format(task['steps'][_id]['right']))
            log.close()
            raise RightException()
        s = subprocess.Popen(params, cwd=step_dir,
            stdout=log, stderr=log)
        s.wait()
        log.close()
        if s.returncode == 0:
            task["steps"][_id]['status'] = "ok"
            client.update_task(task)
        else:
            raise ErrorException()
    except RightException:
        task["status"] = "right_error"
        task["steps"][_id]['status'] = "right_error"
        client.update_task(task)
        exit(0)
    except ErrorException:
        task["status"] = "error"
        task["steps"][_id]['status'] = "error"
        client.update_task(task)
        exit(0)

task["status"] = "ok"
client.update_task(task)
